package com.cnhis.cloudhealth.clinical.util;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Callable;

import org.apache.commons.io.FileUtils;

import com.google.common.base.Function;
import com.google.common.collect.Maps;
@Deprecated
public class CacheService {

	private String CacheLogDir;

	public static void main(String[] args) throws InterruptedException {

		Map map = Maps.newConcurrentMap();
		map.put("k1", "v1");
		CacheService cacheService = new CacheService();
		cacheService.CacheRefreshTimer(9000,new   Function<String, Object>() {

			@Override
			public Object apply(String f) {
				//some process()
				System.out.println("CacheRefreshTimer processed:"+f);
				return null;
			}
		} );
		cacheService.CacheDir="CacheDir_changeStock";
		cacheService.CacheLogDir="CacheLogDir_changeStockLog";
		cacheService.addCache(  map);
		Thread.sleep(600);
		cacheService.addCache(  map);Thread.sleep(700);	cacheService.addCache(  map);
		
	}

	protected void move2Logdir(String f) {
	//	FileUtils.move
		 try {
			FileUtils.moveFileToDirectory(new File(f), new File(this.CacheLogDir), true);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		
	}

	private void addCache(Map map) {
		String f = CacheDir+"\\" + timestampUtil.gettimeStamp_millsec_filenameEncode() + ".txt";
		// TimestampUtils.
		SerializeUtil_prjcli.serilz(map, f);
		
	}

	Timer tmr = new Timer("CacheService");
	private String CacheDir;

	private void CacheRefreshTimer(int freshTimeMillsec, final Function<String, Object> function) {

		tmr.schedule(new TimerTask() {

			@Override
			public void run() {
				ClrCacheRefresh2db(function);

			}
		}, 500, freshTimeMillsec);
		 

	}

	protected void ClrCacheRefresh2db(Function<String, Object> function) {
		File dir=new File(this.CacheDir);
		File[] fa=dir.listFiles();
		for (File f : fa) {
			function.apply(f.getAbsolutePath());
			//move to logdir
			move2Logdir(f.getAbsolutePath());
		}
	}

	private void addCache(String CacheDir, Map map) {
		this.CacheDir=CacheDir;
		String f = CacheDir+"\\" + timestampUtil.gettimeStamp_millsec_filenameEncode() + ".txt";
		// TimestampUtils.
		SerializeUtil_prjcli.serilz(map, f);

	}

}
